﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;

namespace ClassLibrary1.entity
{
    [XmlRoot("booking")]
    public class Booking: BaseEntity
    {
        [XmlElement("car")]
        public Car car { get; set; }

        [XmlElement("client")]
        public Client client { get; set; }

        [XmlElement("cargo")]
        public Cargo cargo { get; set; }
        
        public Booking() 
        {
            int id = 1;
            
            while(true)
            {
                var entity = FindById(id.ToString());
                if (entity == null)
                {
                    this.id = id;
                    return;
                }
                id++;
            }
        }

        public Booking(string id) 
        {
            if (Booking.FindById(id) != null) return;
            int.TryParse(id, out this.id);
        }

        public Booking(string[] mas)
        {
            this.id = new Booking(mas[0]).id;
            Upd(mas.Skip(1).ToArray());
        }

        public static Booking FindById(string id)
        {
            return (Booking)Data.entity.FirstOrDefault(item => item.GetType() == typeof(Booking) && item.id == int.Parse(id));
        }

        public static List<BaseEntity> FindAll()
        {
            return Data.entity.FindAll(item => item.GetType() == typeof(Booking));
        }

        public override void Upd(string[]mas) 
        {
            try
            {
                this.client = Client.FindById(mas[0]);
                if (this.client != null) this.client.booking = this;
            }
            catch (Exception) { }
            try { 
                this.cargo = Cargo.FindById(mas[1]);
                if (this.cargo != null) this.cargo.booking = this;
            }
            catch (Exception) { }
            try
            {
                this.car = Car.FindById(mas[2]);
                if (this.car != null) this.car.booking = this;
            }
            catch (Exception) { }
            
        }

        public override string Write()
        {
            string s = "booking"+" "+ this.id;
            s += " ";
            if (this.cargo != null)s += this.cargo.id.ToString();
            s += " ";
            if (this.client != null)s += this.client.id.ToString();
            s += " ";
            if (this.car != null) s += this.car.id.ToString();
            return s;
        }

        public bool Equals(Booking a)
        {
            if (this.id.Equals(a.id)) return true;
            return false;
        }
    }
}
